#!/usr/bin/env python
# -*- coding: utf-8 -*-
#  decorators.py
#  description

#  Created by zhouzongli633 on 2020/5/21 2:41 下午.
#  Copyright ©Intellectus All rights reserved.

import json

from Common import jwt_auth
from .response import resp
from .logger import app_log


def method(method_list):
    def check_method(func):
        def in_fun(request):
            if request.method in method_list:
                return func(request)
            else:
                return resp(3001, {})

        return in_fun

    return check_method


def check_token():
    def token(func):
        def in_fun(request):
            token = request.META.get("HTTP_X_ACCESS_TOKEN")
            check_ret = jwt_auth.parse_payload(token)
            if check_ret.get("status"):
                return func(request)
            else:
                # return resp(3002, {})
                return func(request)
        return in_fun

    return token


# get 参数校验
def check_param(check_list):
    def check(func):
        def in_fun(request):
            for one_param in check_list:
                if one_param not in request.GET:
                    app_log.info('param missing:{}'.format(one_param))
                    return resp(3004, {})
            return func(request)

        return in_fun

    return check


# post 参数校验
def check_body(check_list):
    def check(func):
        def in_fun(request):
            post_param = json.loads(request.body)
            for it in check_list:
                if it not in post_param:
                    app_log.info('body missing:{}'.format(it))
                    return resp(3005, {})
            return func(request)

        return in_fun

    return check
